# -*- coding: utf-8 -*-
from django.db.models import Q
from rest_framework import serializers

from app.emergency.models import SamplePlan, Material, PlanOutpersion, PlanInpersion
from dvadmin.system.models import Structures, RoadsInfos
from dvadmin.utils.json_response import SuccessResponse, ErrorResponse
from dvadmin.utils.serializers import CustomModelSerializer
from dvadmin.utils.viewset import CustomModelViewSet


class SamplePlanSerializer(CustomModelSerializer):
    """
    专项预案-序列化器
    """
    road_name = serializers.CharField(source='road.cname', read_only=True)
    road_id = serializers.CharField(source='road.id', read_only=True)
    plantype_name = serializers.CharField(source='plantype.name', read_only=True)
    has_config = serializers.SerializerMethodField()

    # 专项预案是否已配置
    # 如果预案设备、外部人员、内部人员均未配置，判定为未配置，否则为已配置
    def get_has_config(self, obj):
        material = Material.objects.filter(plan=obj).count()
        outpersion = PlanOutpersion.objects.filter(plan=obj).count()
        inpersion = PlanInpersion.objects.filter(plan=obj).count()
        return material + outpersion + inpersion > 0

    class Meta:
        model = SamplePlan
        # fields = ['id', 'name', 'plantype', 'road_id', 'road_name']
        fields = '__all__'
        read_only_fields = ["id"]


class SamplePlanCreateUpdateSerializer(CustomModelSerializer):
    """
    操作专项预案  创建/更新时的列化器
    """

    class Meta:
        model = SamplePlan
        fields = '__all__'


class SamplePlanViewSet(CustomModelViewSet):
    """
    专项预案接口
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    queryset = SamplePlan.objects.order_by('-create_datetime')
    serializer_class = SamplePlanSerializer

    def get_plan_by_road(self, request, *args, **kwargs):
        '''
            根据传入路段id，获取构造物其下预案信息
        '''
        road = RoadsInfos.objects.filter(id=kwargs.get('pk')).first()
        instance = SamplePlan.objects.filter(road=road)
        if instance:
            response = SamplePlanSerializer(instance=instance, many=True, request=request)
            total = len(response.data)
            data = dict(road_name=road.cname, road_id=road.id, plan=response.data)
            return SuccessResponse(data=data, total=total, msg="获取成功")
        else:
            return ErrorResponse(msg="数据不存在")
